# user.py
import random
import re
import smtplib
from flask_mail import Mail, Message
from flask import Blueprint, redirect, render_template, request, jsonify, session, url_for, flash

from module_admin.entity.do.role import SysRole
from module_admin.entity.do.user import SysUser, SysUserRole

from sqlalchemy import or_, and_, all_, any_
from flask import current_app

user = Blueprint('user', __name__,url_prefix='/user')


def generate_verification_code():
    # 生成一个0-9之间的随机整数，范围是[0, 9999]
    verification_code = random.randint(0, 9999)
    return str(verification_code).zfill(4)


def send_email(mail_instance, user_email, user_name, vcode):
    message = Message('Registration Confirmation', sender='zj2585306788@163.com', recipients=[user_email])
    message.body = f"""
        Dear {user_name},

        Thank you for registering on our platform.

        Please enter the following verification code to verify your email address:

        {vcode}

        This code will expire in 24 hours.

        Sincerely,
        The UIC Platform Team
        """
    mail_instance.send(message)


@user.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        # 处理 GET 请求，渲染登录页面
        return render_template('login-9.html', title='Sample Login', header='Sample Case')
    else:
        # 处理 POST 请求，用户提交邮箱和密码
        email = request.form.get('email')
        password = request.form.get('password')
        print(email, password)

        # 验证邮箱是否符合特定的域名
        if re.search(r"@mail\.uic\.edu\.hk$|@mail\.uic\.edu\.cn$", email) or re.search(r"@uic\.edu\.hk$", email) or re.search(r"@qq\.com$", email):
            print(111)
            # 根据邮箱和密码查询用户信息
            user = SysUser.query.filter(and_(SysUser.email == email, SysUser.password == password)).first()

            if user:
                # 查询该用户的角色
                user_role = SysUserRole.query.filter_by(user_id=user.user_id).first()
                print(user_role)

                if user_role:
                    # 获取角色信息
                    role = SysRole.query.filter_by(role_id=user_role.role_id).first()
                    print(role.role_name.lower())

                    if role:
                        # 将用户信息存储到 session 中
                        session['name'] = user.user_name
                        session['id'] = user.user_id
                        session['email'] = user.email
                        session['role'] = role.role_name.lower()  # 保存用户角色
                        print(user.email)

                        # 根据角色名称跳转到不同的页面
                        if role.role_name.lower() == 'student':
                            print(111)
                            return redirect(url_for('student.get_student'))  # 假设你有一个student路由
                        elif role.role_name.lower() == 'teacher':
                            return redirect(url_for('teacher.get_teacher'))  # 假设你有一个teacher路由
                        else:
                            flash('Invalid role!', 'danger')
                            return render_template('login-9.html', title='Sample Login', header='Sample Case')
                    else:
                        flash('Role not found!', 'danger')
                        return render_template('login-9.html', title='Sample Login', header='Sample Case')
                else:
                    flash('User role not found!', 'danger')
                    return render_template('login-9.html', title='Sample Login', header='Sample Case')
            else:
                flash('Invalid email or password!', 'danger')
                return render_template('login-9.html', title='Sample Login', header='Sample Case')
        else:
            flash('Invalid email format!', 'danger')
            return render_template('login-9.html', title='Sample Login', header='Sample Case')


# 学生相关的路由



#
@user.route('/logout')
def logout():
    session.pop('name', None)
    session.pop('id', None)
    return redirect(url_for('user.login'))

# @user.route('/register', methods=['GET', 'POST'])
# def register():
#     if request.method == 'GET':
#         return render_template('register-9.html', title='Sample Register', header='Sample Case')
#     else:
#         email = request.form.get('email')
#         _password = request.form.get('password')
#         name = request.form.get('name')
#         print(email, _password, name)
#         if re.search(r"@mail\.uic\.edu\.cn$|@mail\.uic\.edu\.hk$", email):  # 正则
#             if Student.query.filter(Student.email == email).first():  # 邮箱重复
#                 flash('Email repeat!', 'danger')
#                 return render_template('register-9.html', title='Sample Login', header='Sample Case')
#             else:
#                 vcode = generate_verification_code()
#                 print(vcode)
#                 mail = current_app.extensions['mail']
#                 send_email(mail, email, name, vcode)
#                 session['vcode'] = vcode
#                 session['email'] = email
#                 session['name'] = name
#                 session['_password'] = _password
#                 session['type'] = "Student"
#                 return redirect(url_for('user.verify'))
#
#                 # return redirect(url_for('mail.send_email',user_email=email,user_name=name))
#         if re.search(r"@uic\.edu\.hk$", email):
#             if Teacher.query.filter(Teacher.email == email).first():  # 邮箱重复
#                 flash('Email repeat!', 'danger')
#                 return render_template('register-9.html', title='Sample Login', header='Sample Case')
#             else:
#                 vcode = generate_verification_code()
#                 print(vcode)
#                 mail = current_app.extensions['mail']
#                 send_email(mail, email, name, vcode)
#                 session['vcode'] = vcode
#                 session['email'] = email
#                 session['name'] = name
#                 session['_password'] = _password
#                 session['type'] = "teacher"
#                 return redirect(url_for('user.verify'))
#         elif email == 'admin':
#             if Admin.query.filter(Admin.email == email).first():  # 邮箱重复
#                 flash('Email repeat!', 'danger')
#                 return render_template('register-9.html', title='Sample Login', header='Sample Case')
#             else:
#                 vcode = generate_verification_code()
#                 print(vcode)
#                 mail = current_app.extensions['mail']
#                 send_email(mail, email, name, vcode)
#                 session['vcode'] = vcode
#                 session['email'] = email
#                 session['name'] = name
#                 session['_password'] = _password
#                 session['type'] = "admin"
#                 return redirect(url_for('user.verify'))
#         return redirect(url_for('user.login'))
#
#
# @user.route('/verify', methods=['GET', 'POST'])
# def verify():
#     if request.method == 'GET':
#         return render_template('otp-9.html', title='Sample Verify', header='Sample Case')
#     else:
#         d1 = request.form.get('d1')
#         d2 = request.form.get('d2')
#         d3 = request.form.get('d3')
#         d4 = request.form.get('d4')
#         vcode_ = d1 + d2 + d3 + d4
#         vcode = session.get('vcode')
#         password = session.get('_password')
#         email = session.get('email')
#         name = session.get('name')
#         type = session.get('type')
#         print(vcode_)
#         if vcode == vcode_:
#             if type == "Student":
#                 with db.auto_commit():
#                     user = Student(name, email, password)
#                     # 数据库的insert操作
#                     db.session.add(user)
#             if type == "teacher":
#                 with db.auto_commit():
#                     user = Teacher(name, email, password)
#                     # 数据库的insert操作
#                     db.session.add(user)
#             if type == "admin":
#                 with db.auto_commit():
#                     user = Admin(name, email, password)
#                     # 数据库的insert操作
#                     db.session.add(user)
#             return redirect(url_for('user.login'))
#         else:
#             print("wrong")
#             return redirect(url_for('user.register'))
